package com.example.quiz.controller.admin;

import com.example.quiz.common.Result;
import com.example.quiz.model.User;
import com.example.quiz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class UserManageController {

    @Autowired
    private UserService userService;

    @GetMapping("/manage")
    public String managePage() {
        return "admin/user/manage";
    }

    @GetMapping("/api/list")
    @ResponseBody
    public Result<Map<String, Object>> getUserList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        List<User> users = userService.getPagedUsers(page, size);
        int total = userService.getTotalCount();

        Map<String, Object> data = new HashMap<>();
        data.put("list", users);
        data.put("total", total);

        return Result.success(data);
    }

    @PutMapping("/api/role/{id}")
    @ResponseBody
    public Result<Integer> updateUserRole(
            @PathVariable Long id,
            @RequestParam String role) {
        int result = userService.updateRole(id, role);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("更新失败");
    }

    @DeleteMapping("/api/delete/{id}")
    @ResponseBody
    public Result<Integer> deleteUser(@PathVariable Long id) {
        int result = userService.deleteById(id);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("删除失败");
    }
}